﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Orion.Models
{
	public class AdvertiesRepository
	{
		private OrionDBDataContext m_db = new OrionDBDataContext( );

		public IEnumerable< Adverty > GetAllAdverties( )
		{
			var result = from ad in m_db.Adverties
			             orderby ad.AdvDate  
						 select ad;

			return result;
		}

		public void AddAdvertise( Adverty ad )
		{

			m_db.Adverties.InsertOnSubmit( ad );
			m_db.SubmitChanges( );

		}

		public Adverty GetAdvertiseById( int id )
		{
			var result = ( from ad in m_db.Adverties
						  where ad.ID == id
						  select ad ).SingleOrDefault( );

			return result;
		}

		public void UpdateAdvertise( Adverty ad )
		{
			var oldAdvertise = GetAdvertiseById( ad.ID );
			if (oldAdvertise != null)
			{
				//check for if pic was changed
				if( ! string.IsNullOrEmpty( ad.Picture ) )
				{
					oldAdvertise.Picture = ad.Picture;
				}
				oldAdvertise.Title = ad.Title;
				oldAdvertise.ClientName = ad.ClientName;
				oldAdvertise.StartDate = ad.StartDate;
				oldAdvertise.EndDate = ad.EndDate;
				oldAdvertise.TextBody = ad.TextBody;
				oldAdvertise.Valid = ad.Valid;
				
				m_db.SubmitChanges();
			}
		}
	}
}